OS: Windows 10
Editor: Visual Studio Code
Rust version: 1.63.0
enum
之前介紹Rust基本的型別的時候並沒有提到枚舉(Eenumeration),以下皆稱為enum
。
這個是我所知道的enum
,例如C語言
的:
enum ACTION {
ACTION_WALK,
ACTION_ATTACK,
ACTION_JUMP,
};
這個是Rust的enum
:
enum Action {
Walk,
Attack,
Jump,
}
嗯?看起來沒甚麼不一樣,但是它還可以這樣做:
struct Skill {
id: i32,
atk: f32,
}
enum Action {
Walk {x: i32, y: i32},
Attack(Skill),
Jump(f32),
}
這些枚舉的項目稱為變體(variant)。
第一次看到,的確有些困惑,對!我現在就好困惑,從C語言家族過來的我,會覺得這個算是另類的結構(structure)嗎?只是這些不同的結構都被歸類成一種列舉。我目前就先當作他算是另類的結構了,因為它還可以這樣:
impl Action {
fn print(&self) {
match self {
Action::Walk { x, y } => println!("Walk to position: ({}, {})", x, y),
Action::Attack(skill) => println!(
"Attack with skill: {}, attack damage: {}",
skill.id, skill.atk
),
Action::Jump(height) => println!("Jump height is {} meter(s)", height),
}
}
}
PS: 根據教學:「Rust 的枚舉最接近於函式語言的代數型別(algebraic data types),像是 F#、OCaml 與 Haskell。」
像結構一樣,使用方法(Methods),然後我們來測試一下:
struct Skill {
id: i32,
atk: f32,
}
enum Action {
Walk { x: i32, y: i32 },
Attack(Skill),
Jump(f32),
}
impl Action {
fn print(&self) {
match self {
Action::Walk { x, y } => println!("Walk to position: ({}, {})", x, y),
Action::Attack(skill) => println!(
"Attack with skill: {}, attack damage: {}",
skill.id, skill.atk
),
Action::Jump(height) => println!("Jump height is {} meter(s)", height),
}
}
}
fn main() {
let attack = Action::Attack(Skill { id: 129, atk: 20.7 });
attack.print();
let movement = Action::Walk { x: 25, y: 7 };
movement.print();
let jump = Action::Jump(18.0);
jump.print();
}
下面是輸出:
Compiling basic v0.1.0 (D:\projects\rust_learning\basic)
Finished dev [unoptimized + debuginfo] target(s) in 1.22s
Running `target\debug\basic.exe`
Attack with skill: 129, attack damage: 20.7
Walk to position: (25, 7)
Jump height is 18 meter(s)